package com.lechi.web.server.handle;

import com.alibaba.fastjson2.JSON;
import com.lechi.iot.android.entity.InDeviceMessage;
import com.lechi.iot.netty.channel.ITcpChannel;
import com.lechi.web.constants.AppCmdConstants;
import com.lechi.web.framework.util.GuavaCacheUtil;
import com.lechi.web.service.impl.IotDeviceCommond;
import com.lechi.web.system.domain.IotAndroidDeviceBo;
import com.lechi.web.util.LeChiCacheUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * Android报文接收
 */
@Slf4j
@Sharable
public final class AndroidInboundMessageHandler extends SimpleChannelInboundHandler<ByteBuf> implements BaseWeatherInboundHandle {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) {
        String hostName = getHostName(ctx);
        String deviceJson = byteBuf.toString(Charset.defaultCharset());
        log.error("接收Android设备地址：{}========数据:{}", hostName, deviceJson);
        if (deviceJson.contains("apiVersion")) {
            var iotAndroidDeviceBo = JSON.parseObject(deviceJson, IotAndroidDeviceBo.class);
            iotAndroidDeviceBo.setDeviceIp(hostName);
            CompletableFuture.runAsync(IotDeviceCommond.getDeviceMonitorTask(iotAndroidDeviceBo));
            return;
        }
        var deviceMessage = JSON.parseObject(deviceJson, InDeviceMessage.class);
        var androidDeviceSn = deviceMessage.getDeviceSN();
        if (Objects.nonNull(androidDeviceSn)) {
            GuavaCacheUtil.getBiDeviceSnAndIPMap().forcePut(androidDeviceSn, hostName);
            LeChiCacheUtil.getOfflineMap().put(androidDeviceSn, new Date());
            LeChiCacheUtil.getOfflineFlag().put(androidDeviceSn, false);
            ITcpChannel tcpChannel = LeChiCacheUtil.getTcpChannelMap().get(hostName);
            if (tcpChannel != null && Objects.isNull(tcpChannel.getDeviceSn())) {
                CompletableFuture.runAsync(IotDeviceCommond.commond(androidDeviceSn, AppCmdConstants.STARTED));
                tcpChannel.setDeviceSn(androidDeviceSn);
            }
            if (Objects.nonNull(deviceMessage.getUpdateLogId())) {
                deviceMessage.setClientIp(hostName);
                CompletableFuture.runAsync(IotDeviceCommond.getUpgradeLogTask(deviceMessage));
            }
        }
    }
}
